package com.anyext.storage;

import java.util.HashMap;
import java.util.Map;

import com.anyext.storage.policy.DataSourceType;

public class RouterHolder {
	
	private static final ThreadLocal<String> groupName = new ThreadLocal<String>();
	
	private static final ThreadLocal<Object> groupCondition = new ThreadLocal<Object>();
	
	private static final ThreadLocal<DataSourceType> dataSourceType = new ThreadLocal<DataSourceType>();
	
	private static final ThreadLocal<Map<String, Object>> tableRouterHolder = new ThreadLocal<Map<String, Object>>();
	
	public static void useGroup(String name) {
		groupName.set(name);
	}
	
	public static void useGroupCondition(Object condition) {
		groupCondition.set(condition);
	}
	
	public static void useGroup(String groupName, Object condition) {
		useGroup(groupName);
		useGroupCondition(condition);
	}
	
	public static String getGroupName() {
		String name = groupName.get();
		return name == null ? "default" : name;
	}
	
	public static Object getGroupCondition() {
		return groupCondition.get();
	}
	
	public static void useDataSourceType(DataSourceType type) {
		dataSourceType.set(type);
	}
	
	public static DataSourceType getDataSourceType() {
		return dataSourceType.get();
	}
	
	public static void bindTableCondition(String tableAlias, Object condition) {
		Map<String, Object> tableRouter = tableRouterHolder.get();
		if(tableRouter == null) {
			tableRouter = new HashMap<String, Object>();
			tableRouterHolder.set(tableRouter);
		}
		tableRouter.put(tableAlias, condition);
	}
	
	public static Map<String, Object> getTableCondition() {
		return tableRouterHolder.get();
	}
	
	public static void clear() {
		groupName.remove();
		groupCondition.remove();
		dataSourceType.remove();
		tableRouterHolder.remove();
	}
	
}
